package com.example.myapplication;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import java.util.List;

/**
 * 应用使用统计数据上报服务
 * 负责将应用使用统计数据上报到服务器
 */
public class AppUsageUploadService {
    
    private static final String TAG = "AppUsageUploadService";
    private static final String UPLOAD_ENDPOINT = "/device/usage/upload";
    
    private final Context context;
    private final DeviceDataConfig config;
    private final Gson gson;
    private final AppUsageService appUsageService;
    private final DeviceDataUploader deviceDataUploader;
    
    public AppUsageUploadService(Context context) {
        this.context = context.getApplicationContext();
        this.config = new DeviceDataConfig(context);
        this.gson = new Gson();
        this.appUsageService = new AppUsageService(context);
        this.deviceDataUploader = new DeviceDataUploader(context);
    }
    
    /**
     * 上报指定间隔类型的应用使用统计数据
     * @param intervalType 间隔类型 (INTERVAL_DAILY, INTERVAL_WEEKLY, INTERVAL_MONTHLY, INTERVAL_YEARLY, INTERVAL_BEST)
     * @param callback 上传回调
     */
    public void uploadAppUsageData(int intervalType, DeviceDataUploader.UploadCallback callback) {
        if (!appUsageService.hasUsageStatsPermission()) {
            String error = "没有使用统计权限，无法上报数据";
            Log.w(TAG, error);
            if (callback != null) {
                callback.onError(error);
            }
            return;
        }
        
        // 获取使用统计数据
        List<DeviceDataModel.AppUsageData> appUsageDataList = appUsageService.getAppUsageDataForUpload(intervalType);
        
        if (appUsageDataList == null || appUsageDataList.isEmpty()) {
            String error = "没有可上报的使用统计数据";
            Log.w(TAG, error);
            if (callback != null) {
                callback.onError(error);
            }
            return;
        }
        
        // 创建设备数据模型
        DeviceDataModel deviceData = createDeviceDataModel(appUsageDataList, intervalType);
        
        // 上报数据
        deviceDataUploader.uploadData(deviceData, new DeviceDataUploader.UploadCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "应用使用统计数据上报成功: " + response);
                if (callback != null) {
                    callback.onSuccess(response);
                }
            }
            
            @Override
            public void onError(String error) {
                Log.e(TAG, "应用使用统计数据上报失败: " + error);
                if (callback != null) {
                    callback.onError(error);
                }
            }
        });
    }
    
    /**
     * 上报指定间隔类型的应用使用统计数据（同步版本）
     * @param intervalType 间隔类型
     * @return 上传结果
     */
    public DeviceDataUploader.UploadResult uploadAppUsageDataSync(int intervalType) {
        if (!appUsageService.hasUsageStatsPermission()) {
            String error = "没有使用统计权限，无法上报数据";
            Log.w(TAG, error);
            return new DeviceDataUploader.UploadResult(false, null, error);
        }
        
        // 获取使用统计数据
        List<DeviceDataModel.AppUsageData> appUsageDataList = appUsageService.getAppUsageDataForUpload(intervalType);
        
        if (appUsageDataList == null || appUsageDataList.isEmpty()) {
            String error = "没有可上报的使用统计数据";
            Log.w(TAG, error);
            return new DeviceDataUploader.UploadResult(false, null, error);
        }
        
        // 创建设备数据模型
        DeviceDataModel deviceData = createDeviceDataModel(appUsageDataList, intervalType);
        
        // 上报数据
        return deviceDataUploader.uploadDataSync(deviceData);
    }
    
    /**
     * 创建设备数据模型
     */
    private DeviceDataModel createDeviceDataModel(List<DeviceDataModel.AppUsageData> appUsageDataList, int intervalType) {
        DeviceDataModel deviceData = new DeviceDataModel();
        
        // 设置时间戳
        long currentTime = System.currentTimeMillis();
        deviceData.setTimestamp(currentTime);
        deviceData.setCurrentTime(currentTime);
        
        // 设置设备ID和间隔类型信息
        DeviceDataConfig config = new DeviceDataConfig(context);
        String deviceId = config.getDeviceId();
        String intervalTypeName = getIntervalTypeName(intervalType);
        deviceData.setDeviceId(deviceId + "_" + intervalTypeName);
        
        // 设置应用使用统计数据
        deviceData.setAppUsageStats(appUsageDataList);
        
        // 可以添加其他设备信息（如果需要）
        // DeviceDataCollector collector = new DeviceDataCollector(context);
        // collector.collectDeviceInfo(deviceData);
        
        return deviceData;
    }
    
    /**
     * 获取间隔类型名称
     */
    private String getIntervalTypeName(int intervalType) {
        switch (intervalType) {
            case android.app.usage.UsageStatsManager.INTERVAL_DAILY:
                return "DAILY";
            case android.app.usage.UsageStatsManager.INTERVAL_WEEKLY:
                return "WEEKLY";
            case android.app.usage.UsageStatsManager.INTERVAL_MONTHLY:
                return "MONTHLY";
            case android.app.usage.UsageStatsManager.INTERVAL_YEARLY:
                return "YEARLY";
            case android.app.usage.UsageStatsManager.INTERVAL_BEST:
                return "BEST";
            default:
                return "UNKNOWN";
        }
    }
}

